package multiplex.dataaccess.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import multiplex.dataaccess.DaoException;
import multiplex.model.Cadeira;
import multiplex.model.CompraMarcada;

public class CadeiraDao extends AbstractDao {
	public List<Cadeira> getAllFromCompraMarcada(CompraMarcada compraMarcada){

		List<Cadeira> cadeiras = new ArrayList<Cadeira>();
		try{
			PreparedStatement st = getConnection().prepareStatement("SELECT * FROM Cadeira WHERE Compra_id =?");
			st.setInt(1, compraMarcada.getId());		
			ResultSet rs = st.executeQuery();
			if(rs.next()){
				Cadeira cadeira = new Cadeira();
				fillCadeira(cadeira, rs);
				cadeiras.add(cadeira);
			}
			st.close();
		} catch(Exception e){
			throw new DaoException(e);
		}
		return cadeiras;
	}
	public void save(Cadeira cadeira, int compraMarcadaID){
		try{
			PreparedStatement st = getConnection().prepareStatement(
					"INSERT INTO Cadeira (linha, coluna, Compra_id)" +
					"VALUES (?,?,?)", Statement.RETURN_GENERATED_KEYS);
			fillPreparedStatement(st, cadeira, compraMarcadaID);
			st.execute();
			ResultSet rs = st.getGeneratedKeys();
			rs.next();
			cadeira.setID(rs.getInt(1));
			st.close();
		}catch(Throwable e){
			throw new DaoException(e);
		}
	}
	public void remove(Cadeira cadeira){
		try{
			PreparedStatement st = getConnection().prepareStatement(
					"DELETE FROM Cadeira WHERE id=? ");
			st.setInt(1, cadeira.getID());
			st.execute();
			st.close();		
		}catch(Throwable e){
			throw new DaoException(e);
		}	
	}
	
	private void fillCadeira(Cadeira cadeira, ResultSet rs) throws java.sql.SQLException{
		cadeira.setID(rs.getInt("id"));
		cadeira.setLinha(rs.getInt("linha"));
		cadeira.setColuna(rs.getInt("coluna"));
	}
	private void fillPreparedStatement(PreparedStatement st, Cadeira cadeira, int compraMarcadaID) throws java.sql.SQLException{
		st.setInt(1,cadeira.getLinha());
		st.setInt(2,cadeira.getColuna());
		st.setInt(3, compraMarcadaID);
	}
}
